<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/30
 * Time: 20:20
 */

namespace Home\Logic;


use Home\Model\Page;

class MessageLogic
{
    /**
     * 发送消息
     * @param $from_user_id int 创建者
     * @param $to_user_id int 接受方
     * @param $room_id int 房间id
     * @param $model object
     * @return int 0失败 1成功 2已经发送过
     */
    public function sendMessage($from_user_id,$to_user_id,$room_id,$model){
        $count = D('MessageLog')->where(array('user_id'=>$to_user_id,'create_id'=>$from_user_id,'room_id'=>$room_id))->count();
        if($count >0){
            return 2;
        }
        $nickname = D('User')->where(array('id'=>$from_user_id))->getField('nickname');
        $message['title'] = $nickname."邀请你打擂";
        $message['user_id'] = $to_user_id;
        $message['create_id'] = $from_user_id;
        $message['room_id'] = $room_id;
        $message['create_time'] = time();
        $model->table('t_message_log')->add($message);
        return 1;
    }

    /**
     * 分页条件查询
     * @param $map 查询条件
     * @param $pagenumber 页号
     * @param $pagesize 页面大小
     * @return mixed
     */
    public function getByConditionPage($map, $pagenumber, $pagesize)
    {
        $startno = ($pagenumber - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $list = D('MessageLog')
            ->join('LEFT JOIN t_room r ON r.id=t_message_log.room_id')
            ->where($map)->limit($limit)->order('id desc')
            ->field('t_message_log.*,r.password')
            ->select();
        $data['list'] = $list;
        $count = D('MessageLog')->where($map)->count();
        $page = new Page($pagenumber, $count, $pagesize);
        $page = (array)$page;//转换为数组
        $data['page'] = $page;
        return $data;
    }

    /**
     * 处理消息
     * @param $user_id int 用户id
     * @param $message_id int 消息id
     * @param $type int 类型
     * @return int 0失败 1成功 2该消息不存在 3无法处理
     */
    public function process($user_id,$message_id,$type){
        $message = D('MessageLog')->where(array('id'=>$message_id))->find();
        if(!$message){
            return 2;
        }
        if($message['user_id'] != $user_id){
            return 3;
        }
        D('MessageLog')->where(array('id'=>$message_id))->setField('status',$type);
        return 1;
    }
}